from datetime import datetime

from pydantic import BaseModel
from sqlalchemy import Column, Integer, DateTime
from sqlalchemy import String, Float, func
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import Mapped

Base = declarative_base()


class Traffic(Base):
    __tablename__ = 'traffic'
    id = Column(Integer, primary_key=True, autoincrement=True, comment='主键ID')
    timestamp = Column(DateTime, default=func.now(), comment='记录时间戳，默认为当前时间')
    source_port = Column(Integer, comment='源端口号')
    destination_port = Column(Integer, comment='目的端口号')
    protocol = Column(Integer, comment='协议类型')
    flow_duration = Column(Integer, comment='流持续时间')
    total_fwd_packets = Column(Integer, comment='前向总包数')
    total_length_of_fwd_packets = Column(Integer, comment='前向包总长度')
    fwd_packet_length_max = Column(Float, comment='前向包最大长度')
    fwd_packet_length_min = Column(Float, comment='前向包最小长度')
    flow_iat_mean = Column(Float, comment='流平均到达时间间隔')
    flow_iat_std = Column(Float, comment='流到达时间间隔的标准差')
    flow_iat_max = Column(Float, comment='流最大到达时间间隔')
    total_traffic = Column(Integer, comment='总流量')
    anomalous_traffic = Column(Integer, comment='异常流量')
    normal_traffic = Column(Integer, comment='正常流量')
    label = Column(String(50), comment='流量标签，如正常或异常')


class ModelPerformance(Base):
    __tablename__ = "performance"

    id = Column(Integer, primary_key=True, index=True, autoincrement=True, comment="主键ID")
    model_name = Column(String(255), comment="模型文件名")  # 指定长度为255
    type = Column(String(255), comment="指标类型（如macro_avg, weighted_avg）")  # 指定长度为255
    precision = Column(Float, comment="精确度")
    recall = Column(Float, comment="召回率")
    f1_score = Column(Float, comment="F1分数")
    train_support = Column(Integer, comment="训练集样本数")
    test_support = Column(Integer, comment="测试集样本数")
    timestamp = Column(DateTime, default=datetime.utcnow, comment="记录时间戳")


class Requests(Base):
    __tablename__ = "requests"
    id: Mapped[int] = Column(Integer, primary_key=True, autoincrement=True, comment="主键ID")
    total_requests: Mapped[int] = Column(Integer, comment="总请求数")
    normal_requests: Mapped[int] = Column(Integer, comment="正常请求数")
    anomalous_requests: Mapped[int] = Column(Integer, comment="异常请求数")
    timestamp: Mapped[datetime] = Column(DateTime, default=datetime.utcnow, comment="记录时间戳")


class RequestModel(BaseModel):
    id: int
    total_requests: int
    normal_requests: int
    anomalous_requests: int
    timestamp: datetime

    class Config:
        from_attributes = True
